package com.xana.acg.mikomiko.frags.anime;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.alibaba.android.vlayout.layout.StaggeredGridLayoutHelper;
import com.xana.acg.com.app.Fragment;
import com.xana.acg.com.data.DataSource;
import com.xana.acg.com.view.LoadingView;
import com.xana.acg.com.view.RoundImageView;
import com.xana.acg.com.view.recycler.RecyclerAdapter;
import com.xana.acg.com.view.recycler.RecyclerV;
import com.xana.acg.com.view.recycler.VirtualAdapter;
import com.xana.acg.fac.model.biliAnime.AnimeItem;
import com.xana.acg.fac.model.biliAnime.AnimeResp;
import com.xana.acg.fac.model.biliAnime.Hot;
import com.xana.acg.fac.net.NetCallBack;
import com.xana.acg.fac.net.Network;
import com.xana.acg.mikomiko.App;
import com.xana.acg.mikomiko.IndexActivity;
import com.xana.acg.mikomiko.R;
import com.xana.acg.mikomiko.actis.anime.AnimeIndexActivity;
import com.xana.acg.mikomiko.actis.anime.AnimeParseActivity;
import com.xana.acg.mikomiko.actis.anime.AnimeSearchActivity;
import com.xana.acg.mikomiko.views.Banner;
import com.youth.banner.listener.OnBannerListener;

import net.qiujuer.genius.ui.Ui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

public class AnimeFragment extends Fragment implements RecyclerV.OnMoreLoadListener, IndexActivity.OnRefreshListenter {

    @BindView(R.id.recycler)
    RecyclerV recyclerView;

    static final List<?> list = Arrays.asList(R.drawable.i1, R.drawable.i2, R.drawable.i3, R.drawable.i4, R.drawable.i5, R.drawable.i6, R.drawable.bg_ekidora);
    static final List<String> keys = Arrays.asList(
            "游戏人生",
            "某科学的超电磁炮",
            "魔法禁书目录",
            "问题儿童都来异世界",
            "darling in the franxx",
            "命运石之门",
            "从零开始的异世界生活"
    );
    DelegateAdapter mAdapter;
    List<VirtualAdapter> adapters;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_anime;
    }

    @OnClick(R.id.iv_trigger)
    void click(View view){
        a().navTo(AnimeParseActivity.class);
    }


    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        VirtualLayoutManager lm = new VirtualLayoutManager(recyclerView.getContext());
        recyclerView.setLayoutManager(lm);
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        recyclerView.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 10);
        recyclerView.setAdapter(mAdapter = new DelegateAdapter(lm));
        adapters = new ArrayList<>();
        recyclerView.setListener(this);
        initLayout();
    }

     final RecyclerAdapter.AdapterListenerImpl<Hot> clickLis = new RecyclerAdapter.AdapterListenerImpl<Hot>() {
        @Override
        public void onItemClick(RecyclerAdapter.ViewHolder holder, Hot hot) {
            a().navTo(AnimeSearchActivity.class, "uri", hot.title);
        }
    };

    private void initLayout() {
        int dp14 = dp(14);
        int dp10 = dp(10);

        LinearLayoutHelper llh = new LinearLayoutHelper();
        llh.setMarginLeft(dp14);
        llh.setMarginRight(dp14);
        BAdapter bAdapter = new BAdapter(llh);
        bAdapter.add(list);
        adapters.add(bAdapter);

        GridLayoutHelper glh = new GridLayoutHelper(2);
        glh.setMargin(dp14, dp14, dp14, dp14);
        glh.setGap(dp10);
        RAdapter rAdapter = new RAdapter(glh);
        adapters.add(rAdapter);



        GridLayoutHelper glh1 = new GridLayoutHelper(2);
        glh1.setMargin(dp14, dp14, dp14, dp14);
        glh1.setGap(dp10);
        RAdapter rAdapter1 = new RAdapter(glh1);
        adapters.add(rAdapter1);

        IndexAdapter indexAdapter = new IndexAdapter();
        adapters.add(indexAdapter);

        LabelAdapter labelAdapter = new LabelAdapter(new LabelAdapter.Label("精选推荐", "更多"));


        LabelAdapter la = new LabelAdapter(new LabelAdapter.Label("热播番剧", "更多"));


        LabelAdapter la0 = new LabelAdapter(new LabelAdapter.Label("最近更新", "番剧索引"));


        mAdapter.addAdapters(Collections.unmodifiableList(adapters));
        mAdapter.addAdapter(1, labelAdapter);
        mAdapter.addAdapter(3, la);
        mAdapter.addAdapter(5, la0);
        mAdapter.addAdapter(new LoadingAdapter());
    }

    static String[] p = {
            "-1",
            "-1",
            "-1",
            "-1",
            "-1",
            "-1",
            "0",
            "0",
    };

    @Override
    protected void initData() {
        super.initData();

        Network.biliAPI().getAcfunHot().enqueue(new NetCallBack(new DataSource.Callback<List<Hot>>() {
            @Override
            public void fail(String msg) {
                if(ctx!=null)
                 ctx.refreshEnd(msg);
            }

            @Override
            public void ok(List<Hot> datas) {
                if(ctx!=null)
                ctx.refreshEnd(null);
                adapters.get(1).add(datas);
            }
        }));

        Network.biliAPI().getBiliHot().enqueue(new NetCallBack(new DataSource.Callback<List<Hot>>() {
            @Override
            public void fail(String msg) {
                App.showToast(msg);
            }

            @Override
            public void ok(List<Hot> datas) {
                adapters.get(2).add(datas);
            }
        }));

        request(page = 1, false);

    }


    boolean refresh = false;
    private int page;

    private void request(int page, boolean refresh) {
        Call<AnimeResp> call = Network.biliAPI().getAnimes(
                p[0],
                p[1],
                p[2],
                p[3],
                p[4],
                p[5],
                p[6],
                p[7],
                page,
                20
        );
        call.enqueue(new NetCallBack<>(new DataSource.Callback<AnimeResp>() {
            @Override
            public void fail(String msg) {
                App.showToast(msg);
            }

            @Override
            public void ok(AnimeResp resp) {
                if (resp.refresh)
                    adapters.get(3).replace(resp.data.list);
                else
                    adapters.get(3).add(resp.data.list);
            }
        }, refresh));
    }

    public int dp(int dp) {
        return (int) Ui.dipToPx(getResources(), dp);
    }

    @Override
    public void onMoreLoad() {
        request(++page, false);
    }


    IndexActivity ctx;

    @Override
    public void onRefresh(IndexActivity ctx) {
        this.ctx = ctx;
    }

    static class LabelAdapter extends VirtualAdapter<LabelAdapter.Label>{

        public LabelAdapter(Label label){
            add(label);
        }
        @Override
        public int getViewType(int viewType) {
            return R.layout.view_label;
        }

        @Override
        public LayoutHelper onCreateLayoutHelper() {
            LinearLayoutHelper llh0 = new LinearLayoutHelper();
            llh0.setMargin(dp(12), dp(14), dp(12), 0);
            return llh0;
        }

        @Override
        protected ViewHolder<Label> onCreateViewHolder(View view, int viewType) {
            return new VH(view);
        }

        static class Label{
            String label;
            String more;
            Label(String label, String more){
                this.label = label;
                this.more = more;
            }
        }

        static class VH extends VirtualAdapter.ViewHolder<Label>{
            @BindView(R.id.text_label)
            TextView labelView;
            @BindView(R.id.text_more)
            TextView moreView;

            public VH(View itemView) {
                super(itemView);
            }

            @Override
            protected void onBind(Label label) {
                labelView.setText(label.label);
                if(label.more!=null)
                    moreView.setText(label.more);
                else moreView.setVisibility(View.GONE);
            }

            @OnClick(R.id.text_more)
            void click(View view){
                Context ctx = itemView.getContext();
                Intent intent = new Intent(ctx, AnimeIndexActivity.class);
                ctx.startActivity(intent);

            }
        }
    }

    static class BAdapter extends VirtualAdapter<List<?>> {
        public BAdapter(LayoutHelper lh) {
            super(lh);
        }

        @Override
        public int getViewType(int viewType) {
            return R.layout.view_banner;
        }

        @Override
        protected ViewHolder<List<?>> onCreateViewHolder(View view, int viewType) {
            return new VH(view);
        }

        static class VH extends VirtualAdapter.ViewHolder<List<?>> implements OnBannerListener {
            Banner banner;

            public VH(View itemView) {
                super(itemView);
                banner = itemView.findViewById(R.id.banner);
                banner.setOnBannerListener(this);
            }

            @Override
            protected void onBind(List<?> list) {
                banner.setImages(list);
                banner.start();
            }

            @Override
            public void OnBannerClick(int i) {
                Context ctx = itemView.getContext();
                Intent intent = new Intent(ctx, AnimeSearchActivity.class);
                intent.putExtra("key", keys.get(i));
                ctx.startActivity(intent);
            }
        }
    }

    static class RAdapter extends VirtualAdapter<Hot> {

        public RAdapter(LayoutHelper lh) {
            super(lh);
        }

        @Override
        protected ViewHolder<Hot> onCreateViewHolder(View view, int viewType) {
            return new VH(view);
        }

        @Override
        public int getViewType(int viewType) {
            return R.layout.vt_item_anime_hot;
        }

        static class VH extends VirtualAdapter.ViewHolder<Hot>
            implements View.OnClickListener{
            @BindView(R.id.img_cover)
            RoundImageView coverView;
            @BindView(R.id.txt_title)
            TextView titleView;
            Context ctx;
            public VH(View itemView) {
                super(itemView);
                ctx = itemView.getContext();
            }

            String key;

            @Override
            protected void onBind(Hot hot) {
                coverView.setSrc(hot.img);
                titleView.setText(hot.title);
                coverView.getRootView().setOnClickListener(this);
                key = titleView.getText().toString();
                int i = key.indexOf(' ');
                if(i!=-1){
                    key = key.substring(0, i);
                }
            }

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ctx, AnimeSearchActivity.class);
                intent.putExtra("key", key);
                ctx.startActivity(intent);
            }
        }
    }

    public static class IndexAdapter extends VirtualAdapter<AnimeItem> {

        @Override
        public LayoutHelper onCreateLayoutHelper() {
            StaggeredGridLayoutHelper sglh = new StaggeredGridLayoutHelper();
            int dp14 = dp(14);
            sglh.setMargin(dp14, dp14, dp14, dp14);
            sglh.setGap(dp(10));
            sglh.setLane(2);
            return sglh;
        }

        @Override
        public int getViewType(int viewType) {
            return R.layout.item_index_anime;
        }

        @Override
        protected ViewHolder<AnimeItem> onCreateViewHolder(View view, int viewType) {
            return new VH(view);
        }

        static class VH extends VirtualAdapter.ViewHolder<AnimeItem> implements View.OnClickListener {
            @BindView(R.id.iv_img)
            RoundImageView coverView;
            @BindView(R.id.tv_title)
            TextView titleView;

            @BindView(R.id.tv_update)
            TextView updateView;


            String title;

            public VH(View itemView) {
                super(itemView);
            }

            @Override
            protected void onBind(AnimeItem animeItem) {
                coverView.setSrc(animeItem.cover);
                titleView.setText(animeItem.title);
                updateView.setText(animeItem.index_show);
                coverView.getRootView().setOnClickListener(this);
                title = animeItem.title;
                int i = title.indexOf(' ');
                if(i<0)
                    i = title.indexOf(',');
                if(i<0)
                    i = title.indexOf('（');
                if(i>0)
                    title = title.substring(0, i);
            }

            @Override
            public void onClick(View v) {
                Context ctx = v.getContext();
                Intent intent = new Intent(ctx, AnimeSearchActivity.class);
                intent.putExtra("key", title);
                ctx.startActivity(intent);
            }
        }
    }

    @SuppressWarnings("ALL")
    static class LoadingAdapter extends VirtualAdapter {
        public LoadingAdapter(){
            super();
            add(0);
        }

        @Override
        public LayoutHelper onCreateLayoutHelper() {
            return new LinearLayoutHelper();
        }

        @Override
        public int getViewType(int viewType) {
            return R.layout.view_loading;
        }
        @Override
        protected ViewHolder onCreateViewHolder(View view, int viewType) {
            return new VH(view);
        }

        static class VH extends VirtualAdapter.ViewHolder {
            @BindView(R.id.loading)
            LoadingView loadingView;
            public VH(View itemView) {
                super(itemView);
            }

            @Override
            protected void onBind(Object o) {
                loadingView.start();
            }
        }
    }
}
